package ore.example.pokemoninfo.utils;

import com.pixelmonmod.pixelmon.api.pokemon.Pokemon;
import com.pixelmonmod.pixelmon.api.storage.PartyStorage;
import com.pixelmonmod.pixelmon.api.storage.StorageProxy;
import de.tr7zw.nbtapi.NBTItem;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import ore.example.pokemoninfo.Pokemoninfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 在聊天中展示宝可梦信息（悬停查看详细内容）
 * 无需 Adventure / NMS，纯 Spigot 1.21.1 可用
 */
public class ShowPokemonInfoChat {

    public static void broadcastPokemon(Player player, ItemStack item) {
        try {
            NBTItem nbti = new NBTItem(item);
            int index = nbti.getInteger("party_index");

            PartyStorage storage = StorageProxy.getPartyNow(player.getUniqueId());
            if (storage == null) {
                player.sendMessage(ChatColor.RED + "无法获取你的宝可梦信息！");
                return;
            }

            Pokemon pokemon = storage.get(index);
            if (pokemon == null) {
                player.sendMessage(ChatColor.RED + "该位置没有宝可梦！");
                return;
            }

            // 从配置中读取 lore 模板
            CustomConfig config = Pokemoninfo.getPokemonPartyConfig();
            List<String> loreTemplate = config.getConfig().getStringList("lore");

            List<String> loreLines = new ArrayList<>();
            for (String line : loreTemplate) {
                loreLines.add(PlaceholderUtil.replacePlaceholders(line, pokemon).replace('&', '§'));
            }

            // 组合 hover 文本
            StringBuilder hoverText = new StringBuilder();
            for (String line : loreLines) {
                hoverText.append(line).append("\n");
            }

            String pokemonName = pokemon.isShiny()
                    ? "§e✦ " + pokemon.getTranslatedName().getString()
                    : pokemon.getTranslatedName().getString();

            // 创建主消息
            TextComponent base = new TextComponent("§a" + player.getName() + " §7展示了他的宝可梦 ");
            TextComponent poke = new TextComponent("§b[" + pokemonName + "]");

            // 悬停信息
            poke.setHoverEvent(new HoverEvent(
                    HoverEvent.Action.SHOW_TEXT,
                    new ComponentBuilder(hoverText.toString()).create()
            ));

            // 拼接并发送
            base.addExtra(poke);
            for (Player online : Bukkit.getOnlinePlayers()) {
                online.spigot().sendMessage(base);
            }

        } catch (Exception e) {
            player.sendMessage(ChatColor.RED + "展示宝可梦信息时出现错误！");
            e.printStackTrace();
        }
    }
}
